package com.godme.concurrent.util;

import java.util.Random;
import java.util.concurrent.Phaser;

public class PhaserTest {

    static final Random random = new Random();

    static class MyThread extends Thread {
        private final Phaser phaser;

        public MyThread(String name, Phaser phaser){
            super(name);
            this.phaser = phaser;
        }

        @Override
        public void run() {
            try {

                Thread.sleep(random.nextInt(2000));
                System.err.println(getName() + " : arrive");
                phaser.arrive();
            }catch (Exception e){

            }
        }
    }
    static class MyThread2 extends Thread {
        private final Phaser phaser;

        public MyThread2(String name, Phaser phaser){
            super(name);
            this.phaser = phaser;
        }

        @Override
        public void run() {
            try {

                System.err.println(getName() + " : step1");
                Thread.sleep(random.nextInt(2000));
                phaser.arriveAndAwaitAdvance();
                System.err.println(getName() + " : step2");
                Thread.sleep(random.nextInt(2000));
                phaser.arriveAndAwaitAdvance();
                System.err.println(getName() + " : step3");
                Thread.sleep(random.nextInt(2000));
                phaser.arriveAndAwaitAdvance();
                System.err.println(getName() + " : step4");
                Thread.sleep(random.nextInt(2000));
                phaser.arriveAndAwaitAdvance();
                System.err.println(getName() + " : step5");
                Thread.sleep(random.nextInt(2000));
                phaser.arriveAndAwaitAdvance();
                System.err.println(getName() + " : step6");
                Thread.sleep(random.nextInt(2000));
                phaser.arriveAndAwaitAdvance();
                System.err.println(getName() + " : step7");
                Thread.sleep(random.nextInt(2000));
                phaser.arriveAndAwaitAdvance();
                System.err.println(getName() + " : step8");
                Thread.sleep(random.nextInt(2000));
                phaser.arriveAndAwaitAdvance();
            }catch (Exception e){

            }
        }
    }

    public static void main(String[] args) {
        Phaser phaser = new Phaser(5);
        for (int i = 0; i < 5; i++) {
            new MyThread("thread-"+i, phaser).start();
        }
        phaser.awaitAdvance(phaser.getPhase());
        System.err.println("============");
        phaser = new Phaser(5);
        for (int i = 0; i < 5; i++) {
            new MyThread2("thread-"+i, phaser).start();
        }
    }
}
